import { useCall } from '@/components';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Table from 'braft-extensions/dist/table';
import 'braft-extensions/dist/table.css';
import React, { forwardRef, useEffect, useState } from 'react';

const types = {
  default: [
    'undo',
    'redo',
    'separator',
    'line-height',
    'text-color',
    'bold',
    'italic',
    'underline',
    'strike-through',
    'separator',
    'superscript',
    'subscript',
    'remove-styles',
    'emoji',
    'separator',
    'text-indent',
    'text-align',
    'separator',
    'table',
    'list-ul',
    'list-ol',
    'separator',
    'link',
    'separator',
    'hr',
    'separator',
    'clear',
  ],
  simple: [
    'undo',
    'redo',
    'separator',
    'bold',
    'italic',
    'underline',
    'strike-through',
    'superscript',
    'subscript',
    'separator',
    'text-indent',
    'text-align',
    'separator',
    'table',
    'list-ul',
    'list-ol',
    'separator',
  ],
};

BraftEditor.defaultProps = {
  ...(BraftEditor.defaultProps || null),
  controls: types.default,
};

BraftEditor.use(Table({ withDropdown: true }));

/** 富文本组件 */
function SimpleBraftEditor({ value, type, onChange, ...props }, ref) {
  const [state, setState] = useState(BraftEditor.createEditorState(value));
  const handleChange = useCall((newState) => {
    onChange?.(newState.toHTML());
    setState(newState);
  });
  useEffect(() => {
    if (value && state.toHTML() !== value) {
      setState(BraftEditor.createEditorState(value));
    }
  }, [value]);

  return (
    <BraftEditor ref={ref} value={state} onChange={handleChange} controls={types[type] ?? types.default} {...props} />
  );
}

SimpleBraftEditor = forwardRef(SimpleBraftEditor);

export default SimpleBraftEditor;
